package com.kaede.alimama;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONObject;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class AlimamaHelper {
	private static WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_9);
	private static String token;
	private static ExecutorService executor = Executors.newFixedThreadPool(2);
	
	static{
		Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); 
		Logger.getLogger("org.apache.http.client").setLevel(Level.OFF); 
	}
	
	private static void login() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException
	{
        final HtmlPage htmlPage = webClient.getPage("https://login.taobao.com/member/login.jhtml?style=mini&from=alimama&redirectURL=http%3A%2F%2Flogin.taobao.com%2Fmember%2Ftaobaoke%2Flogin.htm%3Fis_login%3d1&full_redirect=true&disableQuickLogin=true");
        
        HtmlTextInput username = (HtmlTextInput)htmlPage.getElementById("TPL_username_1");
        username.setValueAttribute("yehan2004");
        HtmlPasswordInput passowrd = (HtmlPasswordInput)htmlPage.getElementById("TPL_password_1");
        passowrd.setValueAttribute("yuki015314");
        final HtmlButton submit = (HtmlButton)htmlPage.getElementById("J_SubmitStatic");
        executor.submit(new Runnable(){

			public void run() {
				try {
					submit.click();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}});
        Thread.sleep(1000);
        webClient.getPage("http://www.alimama.com/membersvc/my.htm?domain=taobao&service=user_on_taobao&sign_account=bbe30bb7e772d288c351c08b57ebefef");
        token = webClient.getCookieManager().getCookie("_tb_token_").getValue();
	}
	
	private static void doPost() throws IOException
	{
		WebRequest request = new WebRequest(new URL("http://pub.alimama.com/common/adzone/selfAdzoneCreate.json"), HttpMethod.POST);
		request.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.setAdditionalHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		request.setRequestBody("promotion_type=29#29&gcid=8&siteid=7560186&selectact=sel&adzoneid=25416295&_tb_token_="+token);
		webClient.loadWebResponse(request);
	}
	
	private static String parseJson(String json)
	{
		JSONObject dataJson = null;
		try{
			dataJson = new JSONObject(json);
		}catch(Exception e)
		{
			return null;
		}
		String result = "";
		try{
			result = dataJson.getJSONObject("data").getString("sclick");
		}catch(Exception e)
		{
			
		}
		return result;
	}
	
	private static String doGet(String originUrl) throws IOException
	{
		String targetUrl = URLEncoder.encode(originUrl,"UTF-8");
		String url = "http://pub.alimama.com/urltrans/urltrans.json?siteid=7560186&adzoneid=25416295&promotionURL="+targetUrl+ "&t=" + new Date().getTime()+"&_tb_token_=" + token + "&_input_charset=utf-8";
		WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
		request.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		request.setAdditionalHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		String result = webClient.loadWebResponse(request).getContentAsString();
		return result;
	}
	
	public static String getUrl(String originUrl)
	{
		
		try {
			String getResult = doGet(originUrl);
			if(!getResult.startsWith("{"))
			{
				synchronized(webClient)
				{
					getResult = doGet(originUrl);
					if(!getResult.startsWith("{"))
					{
						login();
						Thread.sleep(50);
						doPost();
						Thread.sleep(20);
						getResult = doGet(originUrl);
					}
				}
			}
			return parseJson(getResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args)
	{
		try {
			System.out.println(doGet("http://item.taobao.com/item.htm?spm=a1z09.2.9.24.cPgx4D&id=37294389243&_u=fjru7ba81"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
